package helper

import (
	"cloud-disk/define"
	"crypto/md5"
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	uuid "github.com/satori/go.uuid"
	"math/rand"
	"strings"
	"time"
)

func Md5(s string) string {
	return fmt.Sprintf("%x", md5.Sum([]byte(s)))
}

//GenerateToken 生成token
func GenerateToken(id uint64, identity, name string, second int64) (string, error) {
	uc := define.UserClaim{
		Id:       id,
		Identity: identity,
		Name:     name,
		StandardClaims: jwt.StandardClaims{ // 设置token有效期
			ExpiresAt: time.Now().Add(time.Second * time.Duration(second)).Unix(),
		},
	}

	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, uc)
	signedString, err := claims.SignedString([]byte(define.JwtKey))
	if err != nil {
		return "", err
	}

	return signedString, err
}

//AnalyzeToken 解析token
func AnalyzeToken(token string) (*define.UserClaim, error) {
	uc := new(define.UserClaim)
	claims, err := jwt.ParseWithClaims(token, uc, func(token *jwt.Token) (interface{}, error) {
		return []byte(define.JwtKey), nil
	})

	if err != nil {
		return nil, err
	}

	if !claims.Valid {
		return nil, errors.New("token is invalid")
	}

	return uc, err
}

var CHARS = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
	"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
	"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}

func RandAllString(lenNum int) string {
	str := strings.Builder{}
	length := len(CHARS)
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < lenNum; i++ {
		l := CHARS[rand.Intn(length)]
		str.WriteString(l)
	}
	return str.String()
}

var CODES = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}

func RandCode(lenNum int) string {
	str := strings.Builder{}
	length := len(CODES)
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < lenNum; i++ {
		l := CODES[rand.Intn(length)]
		str.WriteString(l)
	}
	return str.String()
}

func GetUUID() string {
	v4 := uuid.NewV4()
	return v4.String()
}
